var Rank = new Class({
	Implements: Options,
	options: {
		countDisplay: $empty()
	},
	initialize: function(element,options){
		this.setOptions(options);
		this.add(element);
	},
	add: function(element,options) {	
		this.setOptions(options);
		var Rank = this;
		if(element)
		element.each(function(el){
			var bar = el.getChildren('div')[0];
			var data = JSON.decode(bar.get('class'));
			el.store('data', data);

			var rate = data.rank.toFloat();
			width = (rate/10 * 50);
			bar.setStyle('width', width);
			if(data.id){
				Rank.addEvents(el);
			}
			bar.removeProperty('class');
			data.rank = sprintf('%.01f', rate);
			Rank.setDisplay(data.rank);
		});		
	},
	sendRank: function(element){
		var data = element.retrieve('data', $empty());
		var Rank = this;
		
		new Request.JSON({
			url: '/api/rank.json|' + data.id + '|' + data.rank,
			onSuccess: function(json){
				if(json == 'OK'){
					Rank.removeEvents(element);
				}
			}
		}).send();
	},
	addEvents: function(element){
		var Rank = this;
		var bar = element.getChildren('div')[0];
		var data = element.retrieve('data', $empty());
		
		element.addEvent('mousemove', function(e){
			
			var pos = e.page.x - element.getPosition().x;
			pos = Math.round(pos.limit(0,50));
			bar.setStyle('width', pos);
			data.rank = sprintf('%.01f', ((pos/50)*10));
			element.store('data', data);
			Rank.setDisplay(data.rank);
		});

		element.addEvent('click', function(){
			Rank.sendRank.run(element, Rank);
		});
	},
	removeEvents: function(element){
		element.removeEvents();
	},
	setDisplay: function(rank){
		if(this.options.countDisplay != $empty())
			this.options.countDisplay.set('text', rank);
	}
	
});
